package org.budo.dubbo.http.client.java.impl;

import org.budo.dubbo.http.client.java.RequestContext;
import org.budo.dubbo.http.client.java.exception.ApiErrorException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author lmw-2
 */
public class DefaultResponseHandler extends AbstractResponseHandler {
    @Override
    public Object handleResponseBody(RequestContext requestContext) {
        JSONObject responseObject = JSON.parseObject(requestContext.getResponseBody());
        Integer status = responseObject.getInteger("status");
        if (null == status || status > 0) {
            JSONObject resultObject = responseObject.getJSONObject("result");
            String errorDescription = resultObject.getString("error_description");
            String error = resultObject.getString("error");
            ApiErrorException errorException = new ApiErrorException(status, error, errorDescription);

            if (requestContext.getAsync()) {
                requestContext.getApiCallback().fail(errorException, requestContext);
                return null;
            } else {
                throw errorException;
            }
        } else {
            Object result = responseObject.getObject("result", requestContext.getReturnType()); // 结果反序列化
            if (requestContext.getAsync()) {
                requestContext.getApiCallback().success(result, requestContext); // 成功回调
                return null;
            } else {
                return result;
            }
        }
    }
}